package com.yohann.eduservice.controller.front;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yohann.commonutils.jwt.JwtUtils;
import com.yohann.commonutils.result.R;
import com.yohann.commonutils.vo.CourseOrderVo;
import com.yohann.eduservice.client.OrderClient;
import com.yohann.eduservice.entity.EduCourse;
import com.yohann.eduservice.entity.front.CourseVO;
import com.yohann.eduservice.entity.vo.ChapterVo;
import com.yohann.eduservice.entity.vo.CourseInfoVo;
import com.yohann.eduservice.service.EduChapterService;
import com.yohann.eduservice.service.EduCourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author Yohann
 * @since 2020/8/16
 */
@RestController
@RequestMapping("/edu-service/courseFront")
public class CourseFrontController {
    @Autowired
    private EduCourseService courseService;
    @Autowired
    private EduChapterService chapterService;
    @Autowired
    private OrderClient orderClient;

    /**
     * 查询课程
     * @param current
     * @param limit
     * @param courseVO
     * @return
     */
    @PostMapping("getFrontCourse/{current}/{limit}")
    public R pageQueryTeacher(@PathVariable long current,
                              @PathVariable long limit,
                              @RequestBody(required = false) CourseVO courseVO) {
        Page<EduCourse> coursePage = new Page<>(current, limit);
        Map<String, Object> map = courseService.getCourseList(coursePage, courseVO);

        return R.ok().data(map);
    }

    /**
     * 课程详情
     * @param courseId
     * @return
     */
    @GetMapping("getCourseFrontInfo/{courseId}")
    public R getCourseFrontInfo(@PathVariable String courseId, HttpServletRequest request){
        //查询课程信息
        CourseInfoVo courseInfoVo = courseService.getBaseCourseInfo(courseId);
        //查询章节信息
        List<ChapterVo> chapterVoList = chapterService.getChapterVideoById(courseId);

        //查询购买状态
        boolean isBuy = false;
        if(!JwtUtils.getMemberIdByJwtToken(request).isEmpty()){
            isBuy = orderClient.isBuyCourse(courseId, JwtUtils.getMemberIdByJwtToken(request));
        }else {
            return R.error().code(20004).message("请先登录！");
        }

        return R.ok().data("courseInfoVo",courseInfoVo).data("chapterVoList",chapterVoList).data("isBuy",isBuy);
    }

    /**
     * 订单中课程详情
     * @param id
     * @return
     */
    @GetMapping("getCourseOrderInfo/{id}")
    public CourseOrderVo getCourseOrderInfo(@PathVariable String id){
        CourseInfoVo course = courseService.getBaseCourseInfo(id);
        CourseOrderVo courseOrderVo = new CourseOrderVo();

        BeanUtils.copyProperties(course,courseOrderVo);

        return courseOrderVo;
    }
}